package com.wutuo.roster.provider.service;

import cn.apestar.ChatInstance;
import cn.apestar.agg.user.info.service.UserService;
import cn.apestar.cloud.api.enums.MessageType;
import cn.apestar.cloud.api.enums.MessageWTType;
import cn.apestar.cloud.api.enums.PeoPleType;
import cn.apestar.core.base.BaseService;
import cn.apestar.core.base.GenericMapper;
import cn.apestar.core.http.AppType;
import cn.apestar.user.api.enums.SexType;
import cn.apestar.user.provider.info.domain.User;
import com.wutuo.child.api.request.ChildRequest;
import com.wutuo.child.api.response.ChildResponse;
import com.wutuo.child.provider.service.ChildService;
import com.wutuo.roster.api.RosterAPIService;
import com.wutuo.roster.api.request.AuditChildApplyRequest;
import com.wutuo.roster.api.request.ParentsRequest;
import com.wutuo.roster.api.request.RosterRequest;
import com.wutuo.roster.api.request.SearchRosterRequest;
import com.wutuo.roster.api.response.RosterResponse;
import com.wutuo.roster.provider.component.RosterUtil;
import com.wutuo.roster.provider.constant.GradeUtil;
import com.wutuo.roster.provider.constant.TgStateEnum;
import com.wutuo.roster.provider.constant.UserRelationTypeEnum;
import com.wutuo.roster.provider.dao.RosterMapper;
import com.wutuo.roster.provider.domain.Roster;
import com.wutuo.tag.provider.dao.TagRelationsMapper;
import com.wutuo.tag.provider.domain.TagRelations;
import com.wutuo.tag.provider.service.TagService;
import com.wutuo.wtservice.api.request.UserServiceRequest;
import com.wutuo.wtservice.provider.service.UserServiceService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 花名册 <br>
 * 类详细说明.
 * <p/>
 * Copyright: Copyright (c) 2016年1月26日 下午10:23:33
 * <p/>
 *
 * @author lvh
 * @version 1.0.0
 */
@Service
public class RosterService extends BaseService<Roster, Long> implements RosterAPIService {

    private Logger logger = LoggerFactory.getLogger(RosterService.class);

    @Autowired
    private RosterMapper rosterMapper;

    @Autowired
    private TagService tagService;

    @Autowired
    private TagRelationsMapper tagRelationsMapper;

    @Autowired
    private UserServiceService userServiceService;

    @Autowired
    private ParentsService parentsService;

    @Autowired
    private ChildService childService;

    @Autowired
    private ChildApplyService childApplyService;

    @Autowired
    private UserService userService;

    @Override
    protected GenericMapper<Roster, Long> getMapper() {

        // TODO Auto-generated method stub
        return rosterMapper;
    }

    /**
     * 新增花名册
     *
     * @param record
     * @return void
     * @author lvh 2016年2月3日 上午11:51:32</br>
     */
    @Transactional
    public void addorUpdate(RosterRequest record) {

        if (record.getId() == null) {
            super.add(record);
        } else
            super.update(record);
        // 新增标签
        if (record.getTag() != null && record.getTag().size() > 0) {
            addTag(record.getTag(), record.getId());
        }
        // 新增家长
        if (record.getParent() != null && record.getParent().size() > 0) {
            addPareant(record.getParent(), record);
        }
        // 新增托管类型
        if (record.getTgTypeList() != null && record.getTgTypeList().size() > 0) {
            addTgType(record.getTgTypeList(), record.getId());
        }
    }

    /**
     * 审核通过
     *
     * @param record
     * @return void
     * @author lvh 2016年2月3日 上午11:51:32</br>
     */
    @Transactional
    public void applyChild(AuditChildApplyRequest record) {

        super.add(record);
        // 新增标签
        if (record.getTag() != null && record.getTag().size() > 0) {
            addTag(record.getTag(), record.getId());
        }
        // 新增家长
        if (record.getParent() != null && record.getParent().size() > 0) {
            addPareantRel(record.getParent(), record);
        }
        // 新增托管类型
        if (record.getTgTypeList() != null && record.getTgTypeList().size() > 0) {
            addTgType(record.getTgTypeList(), record.getId());
        }
        /**
         * 更新申请为已经审核
         */
        if (record != null)
            childApplyService.updateStateSuccess(record.getApplyId());
    }

    /**
     * 新增花名册标签关系表
     *
     * @param rosterId
     * @return void
     * @author lvh 2016年2月3日 上午11:51:41</br>
     */
    public void addTag(List<TagRelations> tag, Long rosterId) {

        tagRelationsMapper.deleteTagRelationsByrosterId(rosterId);
        Map map = new HashMap();
        for (int i = 0; i < tag.size(); i++) {
            TagRelations tagSingle = tag.get(i);
            if (map.containsKey(tagSingle.getId()))
                continue;
            tagSingle.setTagId(tagSingle.getId());
            tagSingle.setId(null);
            tagSingle.setRosterId(rosterId);
            tagRelationsMapper.insert(tagSingle);
            map.put(tagSingle.getTagId(), tag);
        }
    }

    /**
     * 新增家长关系表
     *
     * @return void
     * @author lvh 2016年2月3日 上午11:51:41</br>
     */
    public void addPareantRel(List<ParentsRequest> parents, Roster roster) {

        parentsService.deleteParentsByrosterId(roster.getId());
        Map map = new HashMap();
        for (int i = 0; i < parents.size(); i++) {
            ParentsRequest parent = parents.get(i);
            parent.setRosterId(roster.getId());
            parent.setId(null);
            parent.setCmInstitutiond(roster.getCmInstitutionId());
            parentsService.addorUpdate(parent);

            ChildRequest childRecord = new ChildRequest();
            childRecord.setRosterId(roster.getId());
            childRecord.setUserId(parent.getUserId());
            childRecord.setInstitutionId(roster.getCmInstitutionId());
            childService.addorUpdate(childRecord);
        }
    }

    /**
     * 新增家长关系表
     *
     * @return void
     * @author lvh 2016年2月3日 上午11:51:41</br>
     */
    public void addPareant(List<ParentsRequest> parents, Roster roster) {

        parentsService.deleteParentsByrosterId(roster.getId());
        Map map = new HashMap();
        for (int i = 0; i < parents.size(); i++) {
            ParentsRequest parent = parents.get(i);
            parent.setRosterId(roster.getId());
            parent.setCmInstitutiond(roster.getCmInstitutionId());
            parentsService.addorUpdate(parent);
        }
    }

    /**
     * 新增花名册管护类型关系表
     *
     * @param rosterId
     * @return void
     * @author lvh 2016年2月3日 上午11:51:41</br>
     */
    public void addTgType(List<UserServiceRequest> userList, Long rosterId) {

        userServiceService.deleteUserServiceByrosterId(rosterId);
        Map map = new HashMap();
        for (int i = 0; i < userList.size(); i++) {
            UserServiceRequest userService = userList.get(i);
            if (map.containsKey(userService.getId()))
                continue;
            userService.setRosterId(rosterId);
            userService.setWtServiceId(userService.getId());
            userService.setId(null);
            userServiceService.addorUpdate(userService);
            map.put(userService.getWtServiceId(), userService);
        }
    }

    /**
     * 删除花名册
     *
     * @param id
     * @return void
     * @author lvh 2016年2月3日 下午12:34:08</br>
     */
    public void del(Long id) {

        RosterRequest model = new RosterRequest();
        model.setId(id);
        userServiceService.deleteUserServiceByrosterId(id);
        parentsService.deleteParentsByrosterId(id);
        tagRelationsMapper.deleteTagRelationsByrosterId(id);
        super.delete(model);
    }

    /**
     * 查询
     *
     * @param request
     * @return List<RosterResponse>
     * @author lvh 2016年2月3日 下午12:34:20</br>
     */
    public List<RosterResponse> lisForPage(SearchRosterRequest request) {

        request.setDelFlag(true);
        List<RosterResponse> list = rosterMapper.lisForPage(request);
        RosterUtil.convertToCustomerResponseList(list);
        return list;
    }

    /**
     * 查询
     *
     * @param request
     * @return List<RosterResponse>
     * @author lvh 2016年2月3日 下午12:34:20</br>
     */
    public List<RosterResponse> listChildByState(SearchRosterRequest request) {

        request.setDelFlag(true);
        List<RosterResponse> list = rosterMapper.lisForPage(request);
        return list;
    }

    /**
     * 单独查询孩子
     *
     * @param request
     * @return List<RosterResponse>
     * @author lvh 2016年2月3日 下午12:34:20</br>
     */
    public List<RosterResponse> singleList(SearchRosterRequest request) {

        request.setDelFlag(true);
        List<RosterResponse> list = rosterMapper.singleList(request);
        return list;
    }

    /**
     * 查询
     *
     * @return List<RosterResponse>
     * @author lvh 2016年2月3日 下午12:34:20</br>
     */
    public RosterResponse getRosterById(Long id) {

        SearchRosterRequest request = new SearchRosterRequest();
        request.setId(id);
        request.setDelFlag(true);
        List<RosterResponse> list = rosterMapper.lisForPage(request);
        if (list.size() == 0)
            return null;
        RosterResponse d = RosterUtil.convertToCustomerResponse(list.get(0));
        return d;
    }

    /**
     * 查询家长屁孩列表
     *
     * @param request
     * @return List<RosterResponse>
     * @author lvh 2016年2月3日 下午12:34:20</br>
     */
    public List<ChildResponse> getChildListByPid(SearchRosterRequest request) {

        request.setDelFlag(true);
        List<ChildResponse> list = rosterMapper.getChildListByPid(request);
        RosterUtil.convertToChildResponseList(list);
        return list;
    }

    /**
     * 查询家长屁孩列表
     *
     * @param request
     * @return List<RosterResponse>
     * @author lvh 2016年2月3日 下午12:34:20</br>
     */
    public List getChildListByPidNoTask(SearchRosterRequest request) {

        request.setDelFlag(true);
        List list = rosterMapper.getChildListByPid(request);
        RosterUtil.convertToChildNoTaskResponseList(list);
        return list;
    }

    public List<RosterResponse> list(AuditChildApplyRequest request) {

        if (request.getUserId() == null)
            return Collections.emptyList();
        User user = userService.getUserById(request.getUserId());
        request.setDelFlag(true);
        request.setAccount(user.getAccount());
        List list = rosterMapper.list(request);
        RosterUtil.convertToCustomerResponseList(list);
        return list;
    }

    /**
     * 增加花名册标签
     *
     * @param tagId
     * @param userId
     * @return List
     * @author lvh 2016年2月20日 下午8:16:20</br>
     */
    public void addRoasterAndTagRelations(Long tagId, String userId) {

        if (StringUtils.isEmpty(userId))
            return;
        // TODO Auto-generated method stub
        String[] userIds = userId.split(",");
        tagRelationsMapper.delRoasterAndTagRelations(tagId, userId);
        for (int i = 0; i < userIds.length; i++) {
            TagRelations tagSingle = new TagRelations();
            tagSingle.setTagId(tagId);
            tagSingle.setRosterId(Long.decode(ObjectUtils.toString(userIds[0])));
            tagRelationsMapper.insert(tagSingle);
        }
    }

    /**
     * 删除花名册标签
     *
     * @param tagId
     * @param userId
     * @return List
     * @author lvh 2016年2月20日 下午8:16:20</br>
     */
    public void delRoasterAndTagRelations(Long tagId, String userId) {

        if (StringUtils.isEmpty(userId))
            return;
        // TODO Auto-generated method stub
        tagRelationsMapper.delRoasterAndTagRelations(tagId, userId);
    }

    public int countInstitutionChildren(SearchRosterRequest s) {

        if (s.getCmInstitutionId() == null && s.getCmId() == null) {
            return 0;
        }

        if (s.getCmInstitutionId() != null && s.getCmId() == null) {
            s.setCmId(s.getCmInstitutionId().toString());
        }

        return rosterMapper.countTotalChild(s);
    }

    /**
     * 更新花名册状态
     *
     * @return
     */
    public void updateRosterState(String userId, String type) {

        // TODO Auto-generated method stub
        rosterMapper.updateRosterState(userId, type);
    }

    /**
     * 初始化花名称
     */
    public void initChild(User user) {

        RosterRequest roster = new RosterRequest();
        roster.setName("演示小娃");
        roster.setTgZt(TgStateEnum.TG_ZT.getValue());
        roster.setYear(GradeUtil.getGradeNow());
        roster.setGrade("其他");
        roster.setSex(SexType.FEMALE.getValue());
        roster.setCmInstitutionId(user.getInstitutionId());
        roster.setDelFlag(true);
        rosterMapper.insert(roster);

        List<ParentsRequest> listParent = new ArrayList();
        ParentsRequest p = new ParentsRequest();
        p.setUserName(user.getName());
        p.setUserPhone(user.getPhone());
        p.setUserType(UserRelationTypeEnum.USER_QT.getLongValue());
        p.setInstitutionId(user.getInstitutionId());
        p.setCmInstitutiond(user.getInstitutionId());
        p.setRosterId(roster.getId());
        listParent.add(p);

        parentsService.addorUpdate(p);

        // 发送消息
        ChatInstance.getChat(AppType.APESTAR.getValue())
                .transmissionMessageFromOneToOne(PeoPleType.SYSTEM.getValue(), user.getRingId(),
                        "午托帮小帮主默认为您添加演示小娃信息，您可以通过您的手机号码登陆午托帮家长版体验家长端功能！", MessageType.TXT.getValue(),
                        MessageWTType.PT.getValue());
    }

    @Override
    public Roster find(Long id) {
        return super.find(id);
    }
}
